<template>
  <div class="task-con" :style="{ height: userInfo.jumpFlag != 'erp' ? '100%' : '100vh' }">
    <div class="top-tab">
      <a-tabs v-model:active-key="curPage" @change="tabChange" size="mini">
        <a-tab-pane v-for="item in tabList" :key="item.key">
          <template #title>
            <span>{{ item.label }}</span>
            <span>({{ item.num ? item.num : '0' }})</span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="table-bottom table-gl-w">
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :max-num="5" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getList">
          <template #headerLeft>
            <a-space>
              <!-- <div>合计任务：{{ statictsInfo.sumNum }}条 合计任务费用：￥{{ transNumberToShort(statictsInfo.amtSumAmount, 4) }} </div> -->

              <a-button class="gray-outline" @click="showModal('add')" v-if="curPage != 'SENDING_SAMPLE' && userInfo.jumpFlag != 'erp'">新增任务</a-button>
              <div v-if="curPage == 'SENDING_SAMPLE'">
                <a-radio-group type="button" v-model="sampleStatus" @change="getList">
                  <a-radio value="WAIT_SEND_SAMPLE">待送样</a-radio>
                  <a-radio value="WAIT_RECEIVE_SAMPLE">待收样</a-radio>
                </a-radio-group>
              </div>
              <div style="color: #ee8849; font-size: 12px">提示:超过24小时没有主动验收,系统会自动通过验收,请及时验收!</div>
            </a-space>
          </template>
          <template #tableBody>
            <a-table size="mini" :bordered="{ headerCell: true, wrapper: true }" class="table-two-line" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column title="序号" #cell="{ rowIndex }" :width="50">{{ rowIndex + 1 }}</a-table-column>
                <a-table-column title="任务ID" #cell="{ record }" :width="160">
                  <a-space>
                    <div class="highlight cursor" @click="viewDetial(record)">{{ record.code }}</div>
                    <div v-if="$extract(record.taskRequire, 'isSample')">
                      <span style="color: #979797" class="icon icon-yangpin"></span>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="产品">
                  <a-table-column title="图片" #cell="{ record }" :width="60">
                    <ImgPopover :src="imgUrl(record)">
                      <template #con>
                        <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                      </template>
                    </ImgPopover>
                  </a-table-column>
                  <a-table-column title="SKU" #cell="{ record }" :width="150">
                    <TextLimit position="top" :rows="1" :val="$extract(record, 'product.sku') || '--'" />
                  </a-table-column>
                  <a-table-column title="SPU/类目" #cell="{ record }" :width="100">
                    <TextLimit position="top" :rows="1" :val="$extract(record, 'product.spu') || '--'" />
                    <TextLimit position="top" :rows="1" :val="$extract(record, 'product.category.name') || '--'" />
                  </a-table-column>
                  <!-- <a-table-column title="首入FBA仓日期" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtWarehousing">
                    {{ $setTime($extract(record, 'product.gmtWarehousing')) }}
                  </a-table-column> -->
                  <a-table-column title="采购下单" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchase"> {{ $setTime($extract(record, 'product.gmtPurchase'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                  <a-table-column title="采购入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchaseWarehouse"> {{ $setTime($extract(record, 'product.gmtPurchaseWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                  <a-table-column title="货件发货" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShipmentShipped"> {{ $setTime($extract(record, 'product.gmtShipmentShipped'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                  <a-table-column title="货件入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShippmentWarehouse"> {{ $setTime($extract(record, 'product.gmtShippmentWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                </a-table-column>
                <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column>
                <a-table-column title="服务内容" #cell="{ record }" :width="80">
                  <TextLimit :val="$extract(record, 'taskRequire.serContent')" :rows="1" position="top" />
                </a-table-column>
                <a-table-column title="执行周期" #cell="{ record }" :width="80">{{ $extract(record, 'taskRequire.executeCycle') }}天 </a-table-column>
                <a-table-column title="任务费用" #cell="{ record }" :width="80">
                  <div style="color: red">￥{{ $extract(record, 'amtCost') }}</div>
                </a-table-column>
                <a-table-column title="任务雇主" #cell="{ record }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="employer.name"> {{ $extract(record, 'employer.name') }} </a-table-column>
                <a-table-column title="任务创建人" #cell="{ record }" :width="80"> {{ record.createUname ? record.createUname : '--' }} </a-table-column>
                <a-table-column title="乙方" #cell="{ record }" :width="80"> {{ $extract(record, 'takeCompany.companyShortName') || '--' }} </a-table-column>
                <a-table-column :width="130" v-if="curPage != 'WAIT_VERIFY' && curPage != 'FINISHED'">
                  <template #title>
                    <a-popover content="预计交付日期根据执行周期来计算，从收到样品开始计算，无需寄送样品的任务就从乙方接单开始计算">
                      <p>
                        <span>预计交付日期</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>

                  <template #cell="{ record }">
                    <div>{{ $setTime(record.gmtPlanDelivery, 'YYYY-MM-DD') }}</div>
                    <div v-if="record.gmtPlanDelivery">
                      <div style="color: red" v-if="!toCheckDay(record.gmtPlanDelivery).type">超时{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                      <div class="highlight" v-else>剩余{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                    </div>
                  </template>
                </a-table-column>

                <a-table-column :width="130" v-if="['FINISHED'].includes(curPage)">
                  <template #title>
                    <a-popover content="实际执行周期，是指该任务收到样品到任务完成，总共所花费的时间，无需寄送样品的任务从接单开始计算。">
                      <p>
                        <span>实际执行周期</span>
                        <icon-question-circle />
                      </p>
                    </a-popover>
                  </template>

                  <template #cell="{ record }"> {{ transitionTime(record.executeTime) }} </template>
                </a-table-column>

                <!-- <a-table-column title="优先级" #cell="{ record }" :width="60">
                  <div class="level-btn level-1" v-if="record.priority === 'URGENT'"> 急 </div>
                  <div class="level-btn level-2" v-else-if="record.priority === 'HIGH'"> 高 </div>
                  <div class="level-btn level-3" v-else-if="record.priority === 'MIDDLE'"> 中 </div>
                  <div class="level-btn level-4" v-else> 低 </div>
                </a-table-column> -->
                <a-table-column title="创建时间" v-if="['WAIT_PUBLISH', 'WAIT_ACCEPT', 'WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY'].includes(curPage)" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtCreate">
                  {{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>
                <a-table-column title="发布时间" v-if="['WAIT_ACCEPT', 'WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'FINISHED', 'NEGOTIATE_TERMINATED'].includes(curPage)" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtPublish">
                  {{ $setTime(record.gmtPublish, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>

                <a-table-column v-if="['NEGOTIATE_TERMINATED', 'TERMINATED'].includes(curPage)" title="终止原因" #cell="{ record }" :width="80">
                  <TextLimit position="top" :row="1" :Val="record.terminateReason" />
                </a-table-column>
                <a-table-column v-if="['NEGOTIATE_TERMINATED', 'TERMINATED'].includes(curPage)" title="备注理由" #cell="{ record }" :width="80">
                  <TextLimit position="top" :row="1" :Val="record.terminateRemark" />
                </a-table-column>

                <a-table-column title="接单时间" v-if="['SENDING_SAMPLE', 'WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'FINISHED'].includes(curPage)" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtTake">
                  {{ $setTime(record.gmtTake, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY'].includes(curPage)" title="到样时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSampleDelivery">
                  {{ $setTime(record.gmtSampleDelivery, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['EXECUTING', 'WAIT_VERIFY'].includes(curPage)" title="排期时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSchedule">
                  {{ $setTime(record.gmtSchedule, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['FINISHED'].includes(curPage)" title="完成时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtFinish">
                  {{ $setTime(record.gmtFinish, 'YYYY/MM/DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="curPage != 'SENDING_SAMPLE'" title="状态" #cell="{ record }" :width="80">
                  {{ filterStatus(record.status) }}
                </a-table-column>

                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样地址" #cell="{ record }" :width="130">
                  <div>
                    {{ $extract(record, 'sendSample.sampleAddress.stateOrRegion') }}
                    {{ $extract(record, 'sendSample.sampleAddress.city') }}
                  </div>
                  <div>
                    {{ $extract(record, 'sendSample.sampleAddress.address') }}
                  </div>
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样方式" #cell="{ record }" :width="130">
                  <a-space>
                    <div v-if="$extract(record, 'sendSample.sendType')">{{ $extract(record, 'sendSample.sendType') != 'DOOR_DELIVERY' ? '快递' : '送货上门' }}</div>
                    <div v-else>--</div>
                    <div @click="editAddress(record)"> <icon-edit /> </div>
                  </a-space>
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送出日期" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSend" #cell="{ record }" :width="130">
                  {{ $setTime($extract(record, 'sendSample.gmtSend'), 'YYYY/MM/DD') }}
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="物流商/跟踪号" #cell="{ record }" :width="130">
                  <div>{{ $extract(record, 'sendSample.logistics') ? $extract(record, 'sendSample.logistics') : '--' }}</div>
                  <div>{{ $extract(record, 'sendSample.trackingNumber') ? $extract(record, 'sendSample.trackingNumber') : '--' }}</div>
                </a-table-column>

                <a-table-column title="留言" #cell="{ record }" :width="80">
                  <a-space>
                    <div>{{ getNum(record.leaveMsgList) }}</div>
                    <div>
                      <div v-if="record.hasPartbNewLeaveMsg == null || record.hasPartbNewLeaveMsg == false">
                        <icon-message @click="showMsgModal(record)" class="cursor" :style="{ fontSize: '18px' }" />
                      </div>
                      <div v-else>
                        <a-badge :count="1" dot :offset="[2, -2]">
                          <icon-message @click="showMsgModal(record)" class="cursor" :style="{ color: '#f59a23', fontSize: '18px', verticalAlign: '-3px' }" />
                        </a-badge>
                      </div>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="评价" #cell="{ record }" :width="80" v-if="['FINISHED'].includes(curPage)">
                  <a-button v-if="!record.evaluationLevel" type="text" @click="showEvaluate(record)">去评价</a-button>
                  <div v-else>
                    <a-popover>
                      <a-space>
                        <span class="icon icon-pinpai" style="color: #f7ba1e"></span>
                        <span>{{ record.evaluationLevel }}</span>
                      </a-space>
                      <template #content>
                        <div style="width: 400px">
                          <a-space>
                            <div>评分：</div>
                            <a-rate size="mini" disabled v-model="record.evaluationLevel" :count="10" allow-half />
                            <div>{{ record.evaluationLevel }}</div>
                          </a-space>
                        </div>
                        <div>
                          <a-textarea v-model="record.evaluation" disabled placeholder="没留下什么看法~~" allow-clear />
                        </div>
                      </template>
                    </a-popover>
                  </div>
                </a-table-column>
                <a-table-column title="操作" #cell="{ record }" :width="120" fixed="right">
                  <a-space>
                    <a-button v-if="record.status" type="text" @click="viewDetial(record)">详情</a-button>
                    <a-button v-if="record.status == 'WAIT_PUBLISH'" type="text" @click="showModal('edit', record)">编辑</a-button>
                    <a-button v-if="record.status == 'WAIT_PUBLISH'" style="color: red" type="text" @click="del(record.id)">删除</a-button>
                    <a-button v-if="['WAIT_ACCEPT', 'SENDING_SAMPLE'].includes(record.status)" type="text" @click="cancel(record.id)">撤回</a-button>
                    <a-button v-if="['EXECUTING', 'WAIT_SCHEDULE'].includes(record.status)" type="text" @click="stop(record)">终止</a-button>
                    <a-button type="text" v-if="['WAIT_VERIFY'].includes(record.status)" @click="acceptTask(record)">验收</a-button>
                    <a-button v-if="record.status == 'NEGOTIATE_TERMINATED' && record.terminateBelong == '乙方'" type="text" @click="negotiate(record)">协商</a-button>
                    <a-button v-if="record.status == 'SENDING_SAMPLE' && record.sendSample && record.sendSample.status == 'WAIT_SEND_SAMPLE'" type="text" @click="editAddress(record)">送样</a-button>
                    <!-- <a-button v-if="record.status == 'FINISHED'" type="text">售后</a-button> -->
                  </a-space>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
  </div>
  <TaskDetail v-if="showTaskDetailModal" :type="taskType" :info="taskDetailInfo" v-model="showTaskDetailModal" @save="sizeChange(20)" />
  <viewDetail v-if="viewTaskDetailModal" v-model="viewTaskDetailModal" :info="taskDetailInfo" @save="getList" />
  <stopTask v-if="showTasklModal" v-model="showTasklModal" :info="taskDetailInfo" @save="getList" />
  <negotiateTask v-if="showNegotiateTasklModal" v-model="showNegotiateTasklModal" :info="taskDetailInfo" @save="getList" />
  <msglist v-if="showMsgListModal" v-model="showMsgListModal" :info="taskDetailInfo" @save="getList" />
  <!-- 验收 -->
  <checkAndAcceptTask v-if="showCheckAndAcceptTasklModal" v-model="showCheckAndAcceptTasklModal" :info="taskDetailInfo" @save="getList" />
  <!-- 修改验收方式 -->
  <editCollectionAddress v-if="showeditCollectionAddressModal" v-model="showeditCollectionAddressModal" :info="taskDetailInfo" @save="getList" />
  <!-- 评价 -->
  <evaluate v-if="showevaluateModal" v-model="showevaluateModal" :info="taskDetailInfo" @save="getList" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { findTaskPage, delTask, revokeTask, countTaskStatus, statTaskFromLocation } from '@/api/task'
  import { Message, Modal } from '@arco-design/web-vue'
  import { transNumberToShort } from '@/utils'
  import useUserStore from '@/store/modules/user'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import TaskDetail from './components/addOrEdit/taskDetail.vue'
  import viewDetail from './components/viewDetail/showDetail.vue'
  import stopTask from './components/stopTask.vue'
  import negotiateTask from './components/negotiateTask.vue'
  import msglist from './components/msgList.vue'
  import checkAndAcceptTask from './components/checkAndAcceptTask.vue'
  import editCollectionAddress from './components/viewDetail/editCollectionAddress.vue'
  import evaluate from './components/evaluate.vue'
  import _ from 'lodash-es'
  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }

  let curPage = ref('WAIT_VERIFY')
  let tabList = ref([
    { label: '待验收', num: '0', key: 'WAIT_VERIFY', countKey: 'waiteVerifyNum' },
    { label: '全部', num: '0', key: '', countKey: 'allNum' },
    { label: '待发布', num: '0', key: 'WAIT_PUBLISH', countKey: 'waitPublishNum' },
    { label: '待接单', num: '0', key: 'WAIT_ACCEPT', countKey: 'waitAcceptNum' },
    { label: '送样中', num: '0', key: 'SENDING_SAMPLE', countKey: 'sendingSampleNum' },
    { label: '待执行', num: '0', key: 'WAIT_SCHEDULE', countKey: 'waitScheduleNum' },
    { label: '执行中', num: '0', key: 'EXECUTING,WAIT_CHECK', countKey: 'executingNum' },
    { label: '已完成', num: '0', key: 'FINISHED', countKey: 'finishedNum' },
    { label: '协商终止', num: '0', key: 'NEGOTIATE_TERMINATED', countKey: 'negotiateTerminatedNum' },
    { label: '已终止', num: '0', key: 'TERMINATED', countKey: 'terminatedNum' },
  ])
  let statictsInfo: any = ref({})
  let searchValue: any = ref({})
  let tableList = ref([{}])
  let loading = ref(false)
  let id = ref()
  let taskType: any = ref('')
  let sampleStatus: any = ref('')
  let taskDetailInfo: any = ref({})
  let showTaskDetailModal = ref(false)
  let viewTaskDetailModal = ref(false)
  let showTasklModal = ref(false)
  let showNegotiateTasklModal = ref(false)
  let showMsgListModal = ref(false)
  let showCheckAndAcceptTasklModal = ref(false)
  let showeditCollectionAddressModal = ref(false)
  let showevaluateModal = ref(false)
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  let userInfo = useUserStore()
  const filterItem: any = ref([
    {
      type: 'input_keyword',
      key: 'codeList',
      keyItems: [
        { label: '任务ID', value: 'codeList' },
        { label: '服务内容', value: 'serContentList' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '任务ID',
      width: 180,
      isMultiple: true,
    },
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'employerName',
      keyItems: [
        { label: '任务雇主', value: 'employerName' },
        { label: '任务创建人', value: 'createUname' },
      ],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '任务雇主',
      width: 110,
    },
    {
      type: 'input_search',
      key: 'takeCompanyName',
      keyWidth: '110',
      value: ref(),
      placeholder: '接单组织',
      width: 160,
    },
    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: 110,
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报设计', value: 'POSTER_SHOP_DESIGN' },
        { label: '换钻调色', value: 'CHANGE_DIAMOND_COLOR' },
        { label: '手绘设计', value: 'HAND_DRAWN_DESIGN' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },
    {
      type: 'keyword_date_range_custom',
      key: 'gmtPlanDelivery',
      keyItems: [{ label: '预计交付日期', value: 'gmtPlanDelivery' }],
      keyWidth: '130',
      value: ref(),
      label: '预计交付日期',
      width: 240,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtTake',
      keyItems: [
        { label: '接单时间', value: 'gmtTake' },
        { label: '到样时间', value: 'gmtSampleDelivery' },
      ],
      keyWidth: '130',
      label: '接单时间',
      value: ref(),
      width: 240,
    },
    {
      type: 'keyword_date_range_custom',
      key: 'product.gmtPurchase',
      keyItems: [
        { label: '采购下单时间', value: 'product.gmtPurchase' },
        { label: '采购入库时间', value: 'product.gmtPurchaseWarehouse' },
        { label: '货件发货时间', value: 'product.gmtShipmentShipped' },
        { label: '货件入库时间', value: 'product.gmtShippmentWarehouse' },
      ],
      keyWidth: '130',
      label: '采购下单时间',
      value: ref(),
      width: 240,
    },
    // {
    //   key: 'priority',
    //   label: '紧急程度',
    //   value: ref(),
    //   type: 'select',
    //   width: '100%',
    //   optionItems: [
    //     { label: '急', value: 'URGENT' },
    //     { label: '高', value: 'HIGH' },
    //     { label: '中', value: 'MIDDLE' },
    //     { label: '低', value: 'LOW' },
    //   ],
    //   attrs: {
    //     'allow-clear': true,
    //   },
    // },
  ])

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)
    console.log(info)

    if (searchValue.value.startDate) {
      searchValue.value.startDate = new Date(`${searchValue.value.startDate} 00:00:00`).valueOf()
      searchValue.value.endDate = new Date(`${searchValue.value.endDate} 23:59:59`).valueOf()
    }
    if (searchValue.value.codeList) {
      searchValue.value.codeList = searchValue.value.codeList.split(',')
    } else {
      searchValue.value.codeList = []
    }

    // if (searchValue.value.gmtPurchase123) {
    //   searchValue.value.gmtExpectDeliveryStart = new Date(`${searchValue.value.gmtPurchase123.split(',')[0]} 00:00:00`).valueOf()
    //   searchValue.value.gmtExpectDeliveryEnd = new Date(`${searchValue.value.gmtPurchase123.split(',')[1]} 23:59:59`).valueOf()
    // } else {
    //   delete searchValue.value.gmtExpectDeliveryStart
    //   delete searchValue.value.gmtExpectDeliveryEnd
    // }

    getList()
  }
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }

  const getList = async () => {
    let params = {
      ...searchValue.value,
      // statusList: curPage.value.split(','),
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    if (params.status == 'SENDING_SAMPLE') {
      params.sampleStatus = sampleStatus.value
    }

    if (curPage.value) params.statusList = curPage.value.split(',')

    loading.value = true
    const res: any = await findTaskPage(params)
    if (res) {
      tableList.value = res?.data?.records
      pageNation.value.total = res?.data?.total
    }
    getStatusNum()
    loading.value = false
  }

  const toCheckDay = (time: any) => {
    let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
    let newDate = new Date().valueOf()
    let timeStr = 0
    if (date > newDate) {
      timeStr = date - newDate
    } else {
      timeStr = newDate - date
    }
    const formatTimeFromTimestamp = (timestamp: number) => {
      let text = ''
      const days = Math.floor(timestamp / (60 * 60 * 24 * 1000))
      const hours = Math.floor((timestamp % (60 * 60 * 24 * 1000)) / (60 * 60 * 1000))
      text = days > 0 ? `${days}天${hours}小时` : `${Math.abs(hours)}小时`
      return text
    }
    if (date - newDate < 0) {
      return {
        type: false,
        day: formatTimeFromTimestamp(timeStr),
      }
    } else {
      return {
        type: true,
        day: formatTimeFromTimestamp(timeStr),
      }
    }
  }

  const filterStatus = (val: string) => {
    let statusList = [
      { label: '待验收', num: '81', key: 'WAIT_VERIFY', countKey: 'waiteVerifyNum' },
      { label: '全部', num: '231', key: '', countKey: 'allNum' },
      { label: '待发布', num: '1', key: 'WAIT_PUBLISH', countKey: 'waitPublishNum' },
      { label: '待接单', num: '5', key: 'WAIT_ACCEPT', countKey: 'waitAcceptNum' },
      { label: '送样中', num: '54', key: 'SENDING_SAMPLE', countKey: 'sendingSampleNum' },
      { label: '待执行', num: '65', key: 'WAIT_SCHEDULE', countKey: 'waitScheduleNum' },
      { label: '执行中', num: '78', key: 'EXECUTING', countKey: 'executingNum' },
      { label: '已完成', num: '13', key: 'FINISHED', countKey: 'finishedNum' },
      { label: '协商终止', num: '16', key: 'NEGOTIATE_TERMINATED', countKey: 'negotiateTerminatedNum' },
      { label: '已终止', num: '19', key: 'TERMINATED', countKey: 'terminatedNum' },
      { label: '执行中', num: '19', key: 'WAIT_CHECK', countKey: 'terminatedNum' },
    ]

    let item = statusList.find((item: any) => {
      return item.key == val
    })
    return item?.label || '未知状态'
  }

  const getNum = (list: any) => {
    if (list && list instanceof Array) {
      return list.length > 99 ? '99+' : list.length
    } else {
      return '0'
    }
  }

  const showModal = (type: string, info?: any) => {
    taskType.value = type
    taskDetailInfo.value = info
    showTaskDetailModal.value = true
  }

  const viewDetial = (info: any) => {
    taskDetailInfo.value = info
    viewTaskDetailModal.value = true
  }

  const tabChange = () => {
    pageNation.value.pageNum = 1
    getList()
  }

  const del = (id: string) => {
    Modal.error({
      title: '删除任务',
      content: '请再次确认是否需要删除任务，一旦删除无法撤回请谨慎操作',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await delTask({ idList: [id] })
        if (res.code == 'SUCCESS') {
          Message.success('删除成功')
          getList()
        }
      },
    })
  }
  const cancel = (id: string) => {
    Modal.error({
      title: '撤回任务',
      content: '请再次确认是否要将任务撤回到待发布状态',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const res: any = await revokeTask({ idList: [id] })
        if (res.code == 'SUCCESS') {
          Message.success('撤回成功')
          getList()
        }
      },
    })
  }

  const stop = (info: any) => {
    taskDetailInfo.value = info
    showTasklModal.value = true
  }
  const negotiate = (info: any) => {
    taskDetailInfo.value = info
    showNegotiateTasklModal.value = true
  }

  const showMsgModal = (info: any) => {
    taskDetailInfo.value = info
    showMsgListModal.value = true
  }
  const acceptTask = (info: any) => {
    taskDetailInfo.value = info
    showCheckAndAcceptTasklModal.value = true
  }

  const imgUrl = (data: any) => {
    let arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  const editAddress = (info: any) => {
    taskDetailInfo.value = info
    showeditCollectionAddressModal.value = true
  }

  const showEvaluate = (info: any) => {
    taskDetailInfo.value = info
    showevaluateModal.value = true
  }

  const getStaticsInfo = async () => {
    let params = {
      ...searchValue.value,
      status: curPage.value,
      statLocation: 'J_MY_TASK',
    }
    if (params.status == 'SENDING_SAMPLE') {
      params.sampleStatus = sampleStatus.value
    }
    const res: any = await statTaskFromLocation(params)
    if (res) {
      statictsInfo.value = res?.data || {}
    }
  }

  const getStatusNum = async () => {
    const res: any = await countTaskStatus(searchValue.value)
    let obj = res?.data || {}

    tabList.value.forEach((item: any) => {
      if (item.countKey == 'executingNum') {
        item.num = obj.executingNum + obj.waitCheckNum
      } else {
        item.num = obj[item.countKey] || 0
      }
    })
  }

  const transitionTime = (time: number) => {
    if (time < 0) return '--'
    const minutes = Math.floor((time / (1000 * 60)) % 60)
    const hours = Math.floor((time / (1000 * 60 * 60)) % 24)
    const days = Math.floor(time / (1000 * 60 * 60 * 24))
    return (days > 0 ? `${days}天` : '') + (hours > 0 ? `${hours}小时` : '') + (minutes > 0 ? `${minutes}分钟` : '')
  }

  onMounted(() => {
    getList()
    getStaticsInfo()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }

  .task-con {
    // height: calc(100vh - @menuHeight);
    .top-tab {
      background-color: white;
    }
    .table-bottom {
      height: calc(100vh - @menuAndTabHeight);
    }
  }

  .level-btn {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 12px;
  }

  .level-1 {
    background-color: #ffff80;
    color: black;
  }
  .level-2 {
    background-color: #a30014;
    color: white;
  }
  .level-3 {
    background-color: #d9001b;
    color: white;
  }
  .level-4 {
    background-color: #ec808d;
    color: white;
  }
</style>
